﻿#include "formresponder.h"
#include "ui_formresponder.h"
#include "qstringutils.h"
#include "commconfig.h"

FormResponder::FormResponder(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormResponder)
{
    ui->setupUi(this);
}

FormResponder::~FormResponder()
{
    delete ui;
    saveUiCfg();
}

void FormResponder::setComm(BaseResponder *rep)
{
    _rep=rep;
    QWidget *w=rep->getConfigWidget();
    setCfgWidget(w);
    loadUiCfg();

//    connect(_rep,&BaseResponder::onRequestWithKey,this,&FormResponder::onReceivedData);
    connect(_rep,&BaseResponder::onRequest,this,&FormResponder::onReceivedData);
}

void FormResponder::setCfgWidget(QWidget *w)
{
    QVBoxLayout *vbox = new QVBoxLayout();
    vbox->addWidget(w);
    ui->groupBox->setLayout(vbox);
}

void FormResponder::loadUiCfg()
{
    QString gn=QString("%1_ui").arg(_rep->name());
    RequestCfg cfg=CommConfig::instance().getReqCfg(gn);
    ui->chbRecord->setChecked(cfg.isSave);
    ui->chbHex->setChecked(cfg.isHex);
    ui->txtSend->setText(cfg.curCmd);
}

void FormResponder::saveUiCfg()
{
    QString gn=QString("%1_ui").arg(_rep->name());
    RequestCfg cfg;
    cfg.isSave=ui->chbRecord->isChecked();
    cfg.isHex=ui->chbHex->isChecked();
    cfg.curCmd=ui->txtSend->text();
    CommConfig::instance().setReqCfg(gn,cfg);
}

void FormResponder::onReceivedData(QByteArray arr)
{
    QString recStr=QString("%1").arg(QStringUtils::getFormatString(arr,ui->chbHex->isChecked()));
    if(ui->chbRecord->isChecked())
    {
        qDebug()<<"接收:"<<recStr;
    }

    // 使用HTML格式设置颜色
    QString html = QString("<span style='color:green;'>接收:</span><span>%1</span>").arg(recStr);
    ui->reciveData->append(html);  // 使用 append 追加内容
}

void FormResponder::on_btnClear_clicked()
{
    ui->reciveData->clear();
}

void FormResponder::on_btnSend_clicked()
{
    QByteArray arr=ui->chbHex->isChecked()?QByteArray::fromHex(ui->txtSend->text().toUtf8())
                                         :ui->txtSend->text().toUtf8();
    qDebug()<<"回复:"<<ui->txtSend->text();
    QString html = QString("<span style='color:red;'>回复:</span><span>%1</span>").arg(ui->txtSend->text());
    ui->reciveData->append(html);  // 使用 append 追加内容

    _rep->response(arr);
}
